package com.cicadasmall.support.captch;

import com.cicadasmall.common.constant.Constant;
import com.cicadasmall.common.exception.ServiceException;
import com.cicadasmall.common.func.Fn;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;


/**
 * AbstractValidateCodeService
 *
 * @author Jin
 */
@AllArgsConstructor
public abstract class AbstractValidateCodeService implements ValidateCodeService {

    protected StringRedisTemplate redisTemplate;


    protected abstract String buildCacheKey(String key);

    protected void put(String key, String value) {
        redisTemplate.opsForValue().set(key, value, Constant.VALIDATE_CODE_TIME, TimeUnit.SECONDS);
    }

    protected String get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    protected void remove(String key) {
        redisTemplate.delete(key);
    }

    @Override
    public void verifyCaptcha(String deviceId, String inputCodeValue){
        String cacheCode = get(buildCacheKey(deviceId));
        if (Fn.isNotEmpty(cacheCode)) {
            if (Fn.notEqual(cacheCode, inputCodeValue)) {
                throw new ServiceException("验证码输入错误！");
            } else {
                //验证成功移除验证码
                remove(buildCacheKey(deviceId));
            }
        } else {
            throw new ServiceException("验证码已失效！");
        }
    }

    @Override
    public void verifySmsCode(String deviceId, String mobile, String inputCodeValue){
        verifyCaptcha(deviceId + ":" + mobile, inputCodeValue);
    }
}
